package com.wzb.eye100.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Calendar;
import java.util.Random;

//import java.util.Base64;
import android.text.TextUtils;
import android.util.Base64;

import com.wzb.eye100.interf.WApplication;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
 
/**
 * Des加解密工具类
 *
 * @author Lee
 */
public class DesUtil {
 
//aaaaaa：密钥
 
//private  final byte[] DESkey = lmkProperties.getDesKey().getBytes();// 设置密钥，略去  
//private  final byte[] DESkey = "abcdefgh".getBytes();// 设置密钥，略去  至少8位
 
//bbbb：偏移量
//private  final byte[] DESIV = lmkProperties.getDesIv().getBytes();// 设置向量，略去  
//private  final byte[] DESIV = "12345678".getBytes();// 设置向量，略去  至少8位
 
    static AlgorithmParameterSpec iv = null;// 加密算法的参数接口，IvParameterSpec是它的一个实现
    private static SecretKey key = null;
 
 
    public DesUtil(String desKey, String desIv) throws Exception {
        byte[] DESkey = desKey.getBytes();
        byte[] DESIV = desIv.getBytes();
        DESKeySpec keySpec = new DESKeySpec(DESkey);// 设置密钥参数
        iv = new IvParameterSpec(DESIV);// 设置向量
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
        key = keyFactory.generateSecret(keySpec);// 得到密钥对象
    }
 
    /**
     * 加密
     * @param data 待加密的数据
     * @return 加密后的数据
     * @throws Exception
     */
    public String encode(String data) throws Exception {
        Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
        enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式，给出密钥和向量
        byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
        //BASE64Encoder base64Encoder = new BASE64Encoder();
       // return Base64.getEncoder().encodeToString(pasByte);
        //return base64Encoder.encode(pasByte);

        return Base64.encodeToString(pasByte,Base64.DEFAULT);
    }
 
    /**
     * 解密
     * @param data  解密前的数据
     * @return 解密后的数据
     * @throws Exception
     */
    public String decode(String data) throws Exception {
        Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        deCipher.init(Cipher.DECRYPT_MODE, key, iv);
        //BASE64Decoder base64Decoder = new BASE64Decoder();
        //byte[] pasByte = deCipher.doFinal(base64Decoder.decodeBuffer(data));
       // byte[] pasByte = deCipher.doFinal(Base64.getDecoder().decode(data));
        byte[] pasByte = deCipher.doFinal(Base64.decode(data.getBytes(),Base64.DEFAULT));
        return new String(pasByte, "UTF-8");
    }

    /*
    public static void main(String[] args) throws Exception {
        DesUtil tools = new DesUtil("cLTaiTan", "cLTaiTan");
        String data = "0B24-1761-2500-3149-9BC0-2927-1877-049F33587016D";
        System.out.println("加密:" + tools.encode(data));
 
        String data1 = tools.encode(data);
 
        System.out.println("解密:" + tools.decode(data1));
    }*/

    public static String CLdecode(String msg){
        String result="";
        try {
            DesUtil tools = new DesUtil("cLTaiTan", "cLTaiTan");
            result=tools.decode(msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static void desTest(){
        DesUtil tools = null;
        try {
            tools = new DesUtil("cLTaiTan", "cLTaiTan");
            String data = "0B24-1761-2500-3149-9BC0-2927-1877-049F33587016D";
            LogUtil.logMessage("wzb","encode:" + tools.encode(data));

            String data1 = tools.encode(data);

            LogUtil.logMessage("wzb","decode:" + tools.decode(data1));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public static String getKeyRandNumber(){
        return WApplication.sp.get("license_key","");
    }

    public static void saveKeyRandNumber(String num){
        WApplication.sp.set("license_key",num);
    }

    public static String getKeyCreateDate(){
        return WApplication.sp.get("license_createDate","");
    }

    /**
     * 存转成10进制之后的
     * @param num
     */
    public static void saveKeyCreateDate(String num){
        WApplication.sp.set("license_createDate",num);
    }

    public static int getKeyDayNum(){
        return WApplication.sp.get("license_day",0);
    }

    /**
     * 存转成10进制之后的
     * @param num
     */
    public static void saveKeyDayNum(int num){
        WApplication.sp.set("license_day",num);
    }


    /**
     * result 0: 为空,未注册过
     * result 1: 注册过 但是过期
     * result 2:注册过,还在有效期内
     * @return
     */

    public static int checkKeyStatus(){
        int result=0;
        String createDate=getKeyCreateDate();
        int dayNUm=getKeyDayNum();
        if(TextUtils.isEmpty(createDate)){
            return 0;
        }
        int myd=Integer.valueOf(createDate,10);
        LogUtil.logMessage("wzb","checkKeyStatus myd="+myd);
        int y=2000+myd/10000;
        int m=(myd%10000)/100;
        int d=myd%100;
        LogUtil.logMessage("wzb","y="+y+" m="+m+" d="+d);
        Calendar currCal=Calendar.getInstance();
        Calendar createCal=Calendar.getInstance();
        createCal.set(Calendar.YEAR,y);
        createCal.set(Calendar.MONTH,m-1);
        createCal.set(Calendar.DAY_OF_MONTH,d);

        long diffDay=(currCal.getTime().getTime()-createCal.getTime().getTime())/(1000*60*60*24);
        LogUtil.logMessage("wzb","dayNum="+dayNUm+" diff="+diffDay);
        LogUtil.logMessage("wzb","currCal="+currCal.getTime().getTime());
        LogUtil.logMessage("wzb","create="+createCal.getTime().getTime());
        if(diffDay<=dayNUm){
            return 2;
        }else{
            result=1;
        }


        return result;
    }


    public static boolean checkInputKeyValid(String createDateHexStr,String dayNumHexStr){
        boolean result=false;

        int myd=Integer.valueOf(createDateHexStr,16);
        int dayNUm=Integer.valueOf(dayNumHexStr,16);
        LogUtil.logMessage("wzb","checkInputKeyValid myd="+myd);
        int y=2000+myd/10000;
        int m=(myd%10000)/100;
        int d=myd%100;
        LogUtil.logMessage("wzb","y="+y+" m="+m+" d="+d);
        Calendar createCal=Calendar.getInstance();
        createCal.set(Calendar.YEAR,y);
        createCal.set(Calendar.MONTH,m-1);
        createCal.set(Calendar.DAY_OF_MONTH,d);

        long diffDay=(TimeUtils.getCurrentTimeInLong()-createCal.getTime().getTime())/(1000*60*60*24);
        LogUtil.logMessage("wzb","curr="+TimeUtils.getCurrentTimeInLong());
        LogUtil.logMessage("wzb","create="+createCal.getTime().getTime());
        LogUtil.logMessage("wzb","dayNum="+dayNUm+" diff="+diffDay);
        if(diffDay<=dayNUm){
            return true;
        }else{
            result=false;
        }


        return result;
    }


    public static String stringToMD5(String string) {
        byte[] hash;

        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        LogUtil.logMessage("wzb","stringToMD5:"+hex.toString());
        return hex.toString();
    }

    public static String getCustMd5Str(String md5Str){
        String str="";
        if(md5Str.length()==32){
            str=md5Str.substring(0,4)+"-"+
                    md5Str.substring(4,8)+"-"+
                    md5Str.substring(8,12)+"-"+
                    md5Str.substring(12,16)+"-"+
                    md5Str.substring(16,20)+"-"+
                    md5Str.substring(20,24)+"-"+
                    md5Str.substring(24,28)+"-"+
                    md5Str.substring(28);
        }

        return str;
    }

    public static String getRandomString()
    {
        String s = "";
        Random ran =new Random();
        int r=ran.nextInt(99999999);
        s=String.format("%08d",r);
        LogUtil.logMessage("wzb","getRandomString="+s);
        return s;
    }

}
